<?php
  echo "<pre>";
  $arr= array(
	  array('id'=>1,'name'=>'办公用品','parent_id'=>0),
	  array('id'=>2,'name'=>'打印机','parent_id'=>1),
	  array('id'=>3,'name'=>'惠普打印机','parent_id'=>2),
      array('id'=>7,'name'=>'生活用户','parent_id'=>0),
	  array('id'=>8,'name'=>'抽纸','parent_id'=>7),
      array('id'=>9,'name'=>'心想印抽纸','parent_id'=>8),  
	  array('id'=>4,'name'=>'五金配件','parent_id'=>0),
      array('id'=>5,'name'=>'卫浴','parent_id'=>4),
	  array('id'=>6,'name'=>'水龙头','parent_id'=>5),
  );
  
  function buildTree($cats,$pid=0){
  	$tree=[];
  	foreach($cats as $cat){
  		if($cat["parent_id"]==$pid){
				$children=buildTree($cats,$cat["id"]);
				if($children){
					$cat["children"]=$children;
				}
  			$tree[]=$cat;
  		}
  	}
  	return $tree;
  } 
  
  $trees=buildTree($arr,0);
  
  print_r($trees);


 
 ?>